/**
 * Created by PhpStorm.
 * User:  iyahe@qq.com (天明)
 * Date: 2019/8/1 0001
 * Time: 下午 16:17
 * Description:
 */
import qs from 'qs'
import axios from 'axios'

const defData = {
	key: 'tianming'
}
axios.interceptors.request.use(function (config) {
	config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
	config.data = qs.stringify({
		...config.data,
		...defData
	})
	return config
}, function (error) {
	return Promise.reject(error)
})

class http {
	post($url, $data) {
		return this.init($url, $data, 'post')
	}

	get($url, $data) {
		return this.init($url, $data, 'get')
	}

	init($url, $data, $method = 'post', $option = {}) {
		const remote = window.electron.remote;
		let baseUrl = remote.app.model === 'local' ? '/' : 'http://api.he29.com/';
		return new Promise((resolve, reject) => {
			axios({
				method: $method,
				url: baseUrl + $url,
				data: $data,
				...$option
			}).then(res => {
				resolve(res.data)
			}).catch(e => {
				reject(e)
			})
		})
	}

	check($url, $data, $proxy) {
		return this.init($url, $data, 'get', {
			proxy: $proxy
		})
	}
}

export default (new http())
